package com.tozed.android.launcher.simpleui;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.android.internal.telephony.test.SimulatedRadioControl;
import com.tozed.android.launcher.FirstFrameAnimatorHelper;
import com.tozed.android.launcher.LauncherApplication;
import com.tozed.android.launcher.R;
import com.tozed.android.launcher.Utilities;
import com.tozed.android.launcher.simpleui.SimpleUILauncher.State;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.SystemService;
import android.os.Vibrator;
import android.provider.Telephony;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Advanceable;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SimpleUILauncher extends Activity implements SimpleLauncherModel.Callbacks, 
	View.OnClickListener, View.OnLongClickListener, SimplePageIndicator.NaviPointLayoutChange
{
	static final String TAG = "SimpleUILauncher";
	static final boolean LOGD = false;
	private static boolean DEBUG = true;
	
	private static final int ADVANCE_INTERVAL = 20000;
	//private static final int ADVANCE_MSG = 1;
	private static final int ADVANCE_STAGGER = 250;
	static final int APPWIDGET_HOST_ID = 1024;
	public static final int BUBBLE_VIEW_SPAN = 1;
	public static final String CONTACT_PACKAGE = "com.android.contacts";
	public static final String CONTACT_SHORTCUT_CLSNAME = "com.android.contacts.ContactShortcut";
	public static final Uri HWMSG_TABLE_GROUPCHAT_URI = null;
	public static final Uri HWMSG_TABLE_MESSAGE_URI = null;
	public static final String LAUNCHER_PACKAGE = "com.tozed.android.launcher";
	public static final int MSG_CHANGE_TO_NORMAL = 300;
	public static final boolean NAVIGATION_BAR = false;
	private static final String NEED_ADD_ICON = "ic_add";
	private static final String NEED_ADD_ICON_BG = "bg_gray";
	private static final String PREFERENCES = "launcher.preferences";
	public static final int REMOVE_OUT_LINE_DELAY = 50;
	public static final int REMOVE_OUT_LINE_MESSAGE = 5000;
	private static final int REQUEST_CREATE_DIALER_SHORTCUT = 2001;
	private static final int REQUEST_OPEN_FOLDER = 2003;
	private static final int REQUEST_PICK_APP = 2002;
	private static final String RUNTIME_STATE_CURRENT_SCREEN = "simpleLauncher.current_screen";
	private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "simpleLauncher.add_cell_x";
	private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "simpleLauncher.add_cell_y";
	private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "simpleLauncher.add_container";
	private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "simpleLauncher.add_screen";
	public static final int SIMPLE_APPWIDGET_HOST_ID = 1025;
	private static final int SIMPLE_DIALOG_CREATE = 2000;
	private static final int VIBRATE_DURATION = 35;
	
	//@SuppressLint("NewApi")
	//public static final Uri sAllThreadsUri = Telephony.Threads.CONTENT_URI.buildUpon()
	//		.appendQueryParameter("simple", "true").build();
	
	private static Handler sFolderHandler;
	//private static LocaleConfiguration sLocaleConfiguration;
	private static Handler sSimpleUILauncherHandler;
	private boolean isFromNormal;
	private boolean isWindowHasFocus = true;
	private SimpleAddAdapter mAdapter;
	private LauncherApplication mApp;
	private AppWidgetManager mAppWidgetManager;
	private boolean mAttached = false;
	private boolean mAutoAdvanceRunning = false;
	private View mClickView;
	private AlertDialog.Builder mDialogBuilder;
	private GridView mDialogMenuGrid;
	private View mDialogMenuView;
	private long mDuration;
	private ValueAnimator mEditAnimtor;
	public Button mEditDoneButton;
	private String mEditModeOnClickResponse;
	
	private TextView mHatText;
	private View mHatTip;
	private boolean mHottalkApp = false;
	public String[] mIconBgStrings;
	private LayoutInflater mInflater;
	private boolean mIsFinishBindingItems;
	private ArrayList<UpdateMissNumCallback> mListeners = new ArrayList();
	private boolean mMessageApp = false;
	//private MissedCallContentObserver mMissedCallObserver = null;
	private MotionManager mMotionManager;
	private String mNeedAddedItemName;
	//private NewEmailContentObserver mNewEmailObserver = null;
	//private NewHotTalkContentObserver mNewHotTalkObserver = null;
	//private NewMessageContentObserver mNewMessageObserver = null;
	private SimpleItemInfo mPendingAddInfo = new SimpleItemInfo();
	private ContentObserver mPrivacyModeShakeSwitch = null;
	private ArrayList<Runnable> mOnResumeCallbacks = new ArrayList<Runnable>();
	
	// Related to the auto-advancing of widgets
    private final int ADVANCE_MSG = 1;
    private final int mAdvanceInterval = 20000;
    private final int mAdvanceStagger = 250;
    private long mAutoAdvanceSentTime;
    private long mAutoAdvanceTimeLeft = -1;
    private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
        new HashMap<View, AppWidgetProviderInfo>();

	private State mState = State.NORMAL;
	public static enum State{
		NORMAL, EDIT
	}
	
	private SimpleLauncherAppWidgetHost mSimpleAppWidgetHost;
	public int mSimpleCellHeight;
	public int mSimpleCellWidth;
	private SimpleIconCache mSimpleIconCache;
	private SimpleLauncherModel mSimpleModel;
	private SimplePageIndicator mSimpleQuickNavigation;
	public SimpleWorkspace mSimpleWorkspace;
	
	private boolean mUserPresent = true;
	private Vibrator mVibrator;
	private boolean mVisible = false;
	
	private static LocaleConfiguration sLocaleConfiguration = null;
	
	private Runnable mExitSimpleEditModeRunnable = new Runnable() {
		public void run() {
			exitSimpleEditMode();
		}
	};
	
	public static abstract interface UpdateMissNumCallback{
		public abstract int getMissedNumFromDB(Context context);
		public abstract void updateIcon();
	}
	
	private Runnable mUpdateMissInfoSignRunnable = new Runnable(){
		public void run(){
			ArrayList<UpdateMissNumCallback> list = new ArrayList<UpdateMissNumCallback>();
			
			list.addAll(mListeners);
			for (UpdateMissNumCallback callBack : list){
				if (callBack.getMissedNumFromDB(SimpleUILauncher.this) > 0){
					callBack.updateIcon();
				}
			}
			
			list.clear();
		}
	};
	
	private Runnable mShowToastOnceAtFirstRunnable = new Runnable(){
		public void run(){
			showToast(mEditModeOnClickResponse);
		}
	};
	
	private final BroadcastReceiver mReceiver = new BroadcastReceiver()
	{
		public void onReceive(Context context, Intent intent)
		{
			String str = intent.getAction();
			if (Intent.ACTION_SCREEN_OFF.equals(str))
			{
				mUserPresent = false;
				updateRunning();
				exitSimpleEditMode();
			}else if (Intent.ACTION_USER_PRESENT.equals(str)){
				mUserPresent = true;
				updateRunning();
			}
		}
	};
	
	 @Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		// 判断是否是
		//isFromNormal = HomeSwitcher.handlerIntent();
	    mApp = ((LauncherApplication)getApplication());
	    mAppWidgetManager = AppWidgetManager.getInstance(this);
	    mApp.setAppWidgetManager(mAppWidgetManager);
	    
	    mSimpleAppWidgetHost = new SimpleLauncherAppWidgetHost(this, SIMPLE_APPWIDGET_HOST_ID);
	    mSimpleAppWidgetHost.startListening();
	    mSimpleIconCache = mApp.getSimpleIconCache();
	    mSimpleModel = mApp.setSimpleLauncher(this);
	    checkForLocaleChange(); // 监测语言变化
	    
	    getWindow().requestFeature(1);
	    getWindow().addFlags(512);
	    
	    // 设置视图
	    setContentView(R.layout.simple);
		setUpViews();
		
		mIconBgStrings = getResources().getStringArray(R.array.simpleIconBgArray);
	    mDuration = getResources().getInteger(R.integer.config_simpleWorkspaceUnshrinkTime);
		mDuration = 20;
	    restoreState(savedInstanceState);
	    
	    View allAppsView = findViewById(R.id.allapps);
	    AddApplicationViewCache.getInstance().setAllAppsView(allAppsView);
	    
	    mSimpleModel.forceReload();
	    
	    if (mApp.getShakeAllowed())
	      mPrivacyModeShakeSwitch = new PrivacyModeShakeSwitchContent(new Handler());
	    registerContentObservers();
	    
	    ////////////////////////////////////////////////////////////////////////////////
	    /*
	    if (isMotionDetectAvailable())
	    {
	       mMotionManager = new MotionManager(this);
	      this.mShakeWallpaperMotionResultListener = new MotionManager.IMotionResultListener()
	      {
	        boolean mChangeable = true;
	        boolean mIsChanging = false;

	        public void notifyMotionRecoSuccessed(int paramInt1, int paramInt2)
	        {
	          LogHelper.i("SimpleUILauncher motionType " + paramInt1);
	          if (paramInt1 == MotionManager.TYPE_SHAKE_START_PRIVACY)
	            if (this.mChangeable)
	            {
	              this.mIsChanging = true;
	              this.mChangeable = false;
	              Intent localIntent = new Intent("android.intent.action.STARTUP_PRIVACY_MODE");
	              if (!Utilities.checkApkExist(SimpleUILauncher.this.mApp, localIntent))
	                break label124;
	              localIntent.addFlags(268435456);
	              SimpleUILauncher.this.startActivity(localIntent);
	            }
	          while (true)
	          {
	            if (this.mIsChanging)
	            {
	              this.mIsChanging = false;
	              SimpleUILauncher.this.mHandler.postDelayed(new Runnable()
	              {
	                public void run()
	                {
	                  SimpleUILauncher.1.this.mChangeable = true;
	                }
	              }
	              , 2000L);
	            }
	            return;
	            label124: Log.i(TAG, "SimpleUILauncher PrivacyMode APK does not exist");
	          }
	        }
	      };
	    }
	    */
	    initAddingDialog();
	    sSimpleUILauncherHandler = mHandler;
	    /////////////////////////////////////////////////////////////////////////////////////
	}

	private void setUpViews()
	{
		mInflater = getLayoutInflater();
	    mSimpleWorkspace = ((SimpleWorkspace)findViewById(R.id.workspace_simple));
	    
	    ((FrameLayout)mSimpleWorkspace.getParent()).setBackgroundResource(R.drawable.simple_workspace_background);
	    
	    mSimpleWorkspace.setLauncher(this);
	    mSimpleQuickNavigation = ((SimplePageIndicator)findViewById(R.id.simple_page_indicator));
	    mSimpleQuickNavigation.setSimple(this);
	    
	    findEditDoneButton();
	    
	    Resources res = getResources();
	    int cellGap = res.getDimensionPixelSize(R.dimen.simple_workspace_cell_gap);
	    mSimpleCellWidth = res.getDimensionPixelSize(R.dimen.simple_workspace_cell_width);
	    mSimpleCellHeight = res.getDimensionPixelSize(R.dimen.simple_workspace_cell_height);
	    
	    int cellCount = mSimpleWorkspace.getChildCount();
	    mEditModeOnClickResponse = res.getString(R.string.str_edit_mode_click_toast_text);
	    
	    for (int i = 0; i < cellCount; i++){
	    	SimpleCellLayout cellLayout = ((SimpleCellLayout)mSimpleWorkspace.getChildAt(i));
	        cellLayout.setCellDimensions(mSimpleCellWidth, mSimpleCellHeight, cellGap, cellGap);
	    }
	    
	    if (!NAVIGATION_BAR)
	      updateSimpleUILayout();
	    
	    mHatTip = findViewById(R.id.hat_tip);
	    mHatText = ((TextView)mHatTip.findViewById(R.id.hat_text));
	}
	
	private void findEditDoneButton() 
	{
		mEditDoneButton = ((Button) findViewById(R.id.edit_done_button));
		mEditDoneButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View paramView) {
				if (mState == SimpleUILauncher.State.EDIT && mSimpleWorkspace.getChangeStateAnimatingIsEnd()){
					DoTaskOnceAtFirstOrAtLast.doTaskOnceAtFirst(mExitSimpleEditModeRunnable);
				}	
			}
		});
		
		FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)mEditDoneButton.getLayoutParams();
		lp.bottomMargin = -lp.height;
	}
	
	private void updateSimpleUILayout()
	{
		int size = getResources().getDimensionPixelSize(R.dimen.simple_navigation_bar_size);
		FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)mSimpleQuickNavigation.getLayoutParams();
		lp.bottomMargin += size / 2;
		
		int count = mSimpleWorkspace.getChildCount();
		for (int i = 0; i < count; i++){
			SimpleCellLayout cellLayout = (SimpleCellLayout)mSimpleWorkspace.getChildAt(i);
			cellLayout.setTranslationY(size/2 - cellLayout.getPaddingTop());
		}
		
		//mSimpleQuickNavigation.setLayoutParams(lp); // new
		
		mSimpleQuickNavigation.requestLayout();
		mSimpleWorkspace.requestLayout();
	}
	
	private void initAddingDialog() {
		
		mAdapter = new SimpleAddAdapter(this);
		mDialogBuilder = new AlertDialog.Builder(this);
		String str = getString(R.string.str_add_dialog_title_simple);
		mDialogBuilder.setTitle(str);
		mDialogMenuView = View.inflate(getBaseContext(), R.layout.simple_add_list_view, null);
		mDialogBuilder.setView(mDialogMenuView);
		mDialogMenuGrid = ((GridView) mDialogMenuView.findViewById(R.id.gride));
		mDialogMenuGrid.setAdapter(mAdapter);
	}
	
	// 显示从顶层出来的动画提示文本
	public void showDeleteHatTip()
	{
		mHatTip.setVisibility(View.VISIBLE);
		String str = getString(R.string.str_edit_mode_pop_text);
		mHatText.setText(str);
		mHatText.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_inter));
	}
	
	private void registerContentObservers()
	{
		
	}
	
	/**
     * 恢复之前的状态 如果保存过的话, 在onSaveInstanceState里保存的信息 
     * @param savedState 之前的状态
     */
    private void restoreState(Bundle savedState) 
    {
        if (savedState == null) {
            return;
        }
        
        long addContainer;
        int addScreen;
        
        int curScreen = savedState.getInt("simpleLauncher.current_screen", -1);
        if (curScreen > -1)
          mSimpleWorkspace.setCurrentPage(curScreen);
        
        addContainer = savedState.getLong("simpleLauncher.add_container", -1L);
        addScreen = savedState.getInt("simpleLauncher.add_screen", -1);
        
        if (addContainer != -1 && addScreen > -1)
        {
            mPendingAddInfo.container = addContainer;
            mPendingAddInfo.screen = addScreen;
            mPendingAddInfo.cellX = savedState.getInt("simpleLauncher.add_cell_x");
            mPendingAddInfo.cellY = savedState.getInt("simpleLauncher.add_cell_y");
        }
    }
    
    private void sendAdvanceMessage(long delay)
    {
      mHandler.removeMessages(ADVANCE_MSG);
      Message msg = mHandler.obtainMessage(ADVANCE_MSG);
      mHandler.sendMessageDelayed(msg, delay);
      mAutoAdvanceSentTime = System.currentTimeMillis();
    }
    
    private void updateRunning() 
    {
        boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
        if (autoAdvanceRunning != mAutoAdvanceRunning) {
            mAutoAdvanceRunning = autoAdvanceRunning;
            if (autoAdvanceRunning) {
                long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
                sendAdvanceMessage(delay);
            } else {
                if (!mWidgetsToAdvance.isEmpty()) {
                    mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
                            (System.currentTimeMillis() - mAutoAdvanceSentTime));
                }
                mHandler.removeMessages(ADVANCE_MSG);
                mHandler.removeMessages(0); // Remove messages sent using postDelayed()
            }
        }
    }
    
	private final Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
            if (msg.what == ADVANCE_MSG) {
                int i = 0;
                for (View key: mWidgetsToAdvance.keySet()) {
                    final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
                    final int delay = mAdvanceStagger * i;
                    if (v instanceof Advanceable) {
                       postDelayed(new Runnable() {
                           public void run() {
                               ((Advanceable) v).advance();
                           }
                       }, delay);
                    }
                    i++;
                }
                sendAdvanceMessage(mAdvanceInterval);
            }
		}
	};
	
    void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
        if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
        
        View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
        if (v instanceof Advanceable) {
            mWidgetsToAdvance.put(hostView, appWidgetInfo);
            ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
            updateRunning();
        }else{
        	Log.e(TAG, "addWidgetToAutoAdvanceIfNeeded hostView not Advanceable.");
        }
    }
    
    void removeWidgetToAutoAdvance(View hostView) {
        if (mWidgetsToAdvance.containsKey(hostView)) {
            mWidgetsToAdvance.remove(hostView);
            updateRunning();
        }
    }

    public void removeAppWidget(SimpleLauncherAppWidgetInfo launcherInfo) {
        removeWidgetToAutoAdvance(launcherInfo.hostView);
        launcherInfo.hostView = null;
    }
	
	private void checkForLocaleChange()
	{
		if (sLocaleConfiguration == null)
		{
			new AsyncTask<Void, Void, LocaleConfiguration>(){
				protected LocaleConfiguration doInBackground(Void... unused){
					LocaleConfiguration localeConfiguration = new LocaleConfiguration();
					readConfiguration(SimpleUILauncher.this, localeConfiguration);
					return localeConfiguration;
				}
				
				protected void onPostExecute(LocaleConfiguration result){
					sLocaleConfiguration = result;
					// 递归直到sLocaleConfiguration不为null
					checkForLocaleChange();
				}
				
			}.execute();
			return;
		}
		
		final Configuration config = getResources().getConfiguration();
		
		final String previousLocale = sLocaleConfiguration.locale;
		final String locale = config.locale.toString();
		
		final int previousMcc = sLocaleConfiguration.mcc;
		final int mcc = config.mcc;
		
		final int previousMnc = sLocaleConfiguration.mnc;
		final int mnc = config.mnc;
		
		boolean localeChanged = (!locale.equals(previousLocale) || mcc != previousMcc 
				|| mnc != previousMnc);
		if (localeChanged){
			sLocaleConfiguration.locale = locale;
			sLocaleConfiguration.mcc = mcc;
			sLocaleConfiguration.mnc = mnc;
			
			mSimpleIconCache.flush();
			//loadHotApps();
			
			final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
			new Thread("WriteLocaleConfiguration"){
				public void run(){
					writeConfiguration(SimpleUILauncher.this, localeConfiguration);
				}
			}.start();
		}
	}
	
	private static class LocaleConfiguration{
		public String locale;
		public int mcc = -1;
		public int mnc = -1;
	}
	
	private static void readConfiguration(Context context, LocaleConfiguration configuration)
	{
		DataInputStream in = null;
		try{
			in = new DataInputStream(context.openFileInput(PREFERENCES));
			configuration.locale = in.readUTF();
			configuration.mcc = in.readInt();
			configuration.mnc = in.readInt();
		} catch (FileNotFoundException e){
			// Ignore
		} catch (IOException e) {
			// Ignore
		} finally{
			if (in != null){
				try{
					in.close();
				} catch (IOException e){
					// Ignore
				}
			}
		}
	}
	
	private static void writeConfiguration(Context context, LocaleConfiguration configuration) 
	{
		DataOutputStream out = null;
		try{
			final LocaleConfiguration config = configuration;
			out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
			out.writeUTF(config.locale);
			out.writeInt(config.mcc);
			out.writeInt(config.mnc);
			out.flush();
		} catch (FileNotFoundException e){
			// Ignore
		} catch (IOException e) {
			context.getFileStreamPath(PREFERENCES).delete();
		} finally{
			if (out != null){
				try{
					out.close();
				} catch (IOException e){
					// Ignore
				}
			}
		}
		
	}
	
	// 添加文件夹到工作区
	private void addFolderToWorkspace(SimpleItemInfo itemInfo)
	{
		Log.d(TAG, "addFolderToWorkspace itemInfo=[" + itemInfo + "]");
		
		SimpleFolderIcon folderIcon = (SimpleFolderIcon)mInflater.inflate(R.layout.simple_folder_icon, 
					(ViewGroup)mSimpleWorkspace.getChildAt(itemInfo.screen), false);
		itemInfo.setView(folderIcon);
		
		String strTitle;
		int strResId = -1;
		
		if (itemInfo.title.equals(SimpleFolder.SYSTEM_FOLDER_NAME)){
			folderIcon.setSystemAppFolder(true);
		}else{
			folderIcon.setSystemAppFolder(false);
		}
		
		// Log.e(TAG, "itemInfo Title=[" + itemInfo.title.toString() + "]");
		// 只能通过英文获得res的id
		strResId = getResources().getIdentifier(itemInfo.title.toString(), "string", "com.tozed.android.launcher");
		if (strResId != -1 && strResId != 0){
			try{
				strTitle = getResources().getString(strResId);
			}catch(NotFoundException e){
				strTitle = itemInfo.title.toString();
			}
		}else{
			strTitle = itemInfo.title.toString();
		}
		
		folderIcon.applyAppFromBubbleView(itemInfo, strTitle);
		folderIcon.setOnClickListener(this);
		mSimpleWorkspace.addViewInScreen(folderIcon, itemInfo.screen, itemInfo.cellX, itemInfo.cellY, 1, 1, false);
	}

	// 添加桌面workspace上可添加应用项的视图,对于没有应用项的视图都显示为"添加"视图项
	private void bindNeedAddedItems(SimpleCellLayout cellLayout) 
	{
		int screenIndex = mSimpleWorkspace.indexOfChild(cellLayout);
		boolean[][] occupied = cellLayout.getOccupied();
		
		for (int x = 0; x < 2; x++)
			for (int y = 0; y < 4; y++) {
				if (occupied[x][y] == false)
				{
					// has widget sspace, not needadded bubbleview
					if (false){
						boolean isWidgetOccupied = false;
						if (SimpleLauncherModel.sFavoriteWidgets.size() > 0){
							for (SimpleLauncherAppWidgetInfo appWidget : SimpleLauncherModel.sFavoriteWidgets){
								//Log.d(TAG, "x=" + x + ",appWidget.CellX=" + appWidget.cellX + ";y=" 
								//			+ y + ",appWidget.CellY=" + appWidget.cellY + ",appWidget.SpanX=" + appWidget.spanX 
								//			+ ",appWidget.SpanY=" + appWidget.spanY);
								if (appWidget.cellX == x && appWidget.cellY == y){
									isWidgetOccupied = true;
									// skip x,y space according to spanX spanY
									x += (appWidget.spanX-1);
									y += (appWidget.spanY-1);
									break;
								}
							}
						}
					}
					
					//if (!isWidgetOccupied)
					//{
						//Log.d(TAG, "Add NeedAddedItem x=" + x + ",y=" + y);
						SimpleApplicationInfo app = createNeedAddedItem(screenIndex, x, y);
						SimpleBubbleView bubbleView = (SimpleBubbleView)createBubbleView(R.layout.simple_bubble_view, 
											(ViewGroup)mSimpleWorkspace.getChildAt(screenIndex), app);
						mSimpleWorkspace.addViewInScreen(bubbleView, screenIndex, x, y, 1, 1, false);
					//}
				}
			}
	}
	
	public SimpleApplicationInfo createNeedAddedItem(int screen, int cellX, int cellY) 
	{
		SimpleApplicationInfo appInfo = new SimpleApplicationInfo();
		appInfo.container = SimpleLauncherSettings.SimpleFavorites.CONTAINER_DESKTOP;
		appInfo.intent = null;
		appInfo.itemType = SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_NEED_ADDED;
		appInfo.screen = screen;
		appInfo.cellX = cellX;
		appInfo.cellY = cellY;
		appInfo.title = mNeedAddedItemName;
		appInfo.iconPackage = "bg_gray";
		appInfo.iconResource = "ic_add";
		
		SimpleLauncherModel.sFavoriteItems.add(appInfo);
		return appInfo;
	}
	
	
	// 从外部APP添加完成
	private void completeAddAppFromExternal(PendingAddArguments pendingAddArguments)
	{
	    SimpleApplicationInfo app = mSimpleModel.infoFromAppExternalIntent(this, pendingAddArguments.intent, mPendingAddInfo);
	    if (app == null)
	    {
	      Log.w(TAG, "completeAddAppFromExternal info is null exception intent is =" + pendingAddArguments.intent.toString());
	    }
	    else
	    {
	    	//if (!SimpleUtilities.isCustomizePackage(app.getComponentName().getPackageName()))
	    	//	return;
	    	
	    	removeViewAndItemInfo(mPendingAddInfo);
		    app.container = SimpleLauncherSettings.SimpleFavorites.CONTAINER_DESKTOP;
		    app.cellX = mPendingAddInfo.cellX;
		    app.cellY = mPendingAddInfo.cellY;
		    app.screen = mPendingAddInfo.screen;
		    mSimpleModel.findIconMatch(app);
		    
		    SimpleBubbleView bubbleView = createBubbleView(R.layout.simple_bubble_view, 
		    		(ViewGroup)mSimpleWorkspace.getChildAt(app.screen), app);
		   
		    // 添加到桌面
		    mSimpleWorkspace.addViewInScreen(bubbleView, app.screen, app.cellX, app.cellY, 1, 1, false);
		    
		    // 重新刷新 文件夹内容
		    mApp.getSimpleModel().removeItemFromFolders(mApp, app.intent.getComponent().getClassName());
		    bindFolders(SimpleLauncherModel.sFolders);
		    
		    // 添加到数据库中
		    SimpleLauncherModel.addOrUpdtateItemInDatabase(this, app);
	    }
	    
	    /*
	    mSimpleModel.getWorker().post(new Runnable(){
	      public void run(){
	    	  SimpleUtilities.updateCustomizeAppIcon(SimpleUILauncher.this, null);
	      }
	    });
	    */
	}
	
	// 添加拨号快捷方式完成
	private void completeAddDialerShortcut(PendingAddArguments pendingAddArguments)
	{
		SimpleApplicationInfo app = mSimpleModel.infoFromShortcutIntent(this, pendingAddArguments.intent, mPendingAddInfo);
		
		if (app == null){
			Log.w(TAG, "completeAddDialerShortcut info is null exception args.intent=" + pendingAddArguments.intent.toString());
			return;
		}
		
		removeViewAndItemInfo(mPendingAddInfo);
		SimpleBubbleView bubbleView = createShortcutBubbleView(R.layout.simple_bubble_view,
				(ViewGroup)mSimpleWorkspace.getChildAt(app.screen),app);
		
		mSimpleWorkspace.addViewInScreen(bubbleView, mPendingAddInfo.screen, mPendingAddInfo.cellX,
				mPendingAddInfo.cellY, 1, 1, false);
		
		SimpleLauncherModel.addItemToDatabase(mApp, app, true);
	}
	
	// 从外部添加完成
	private void completeAddFromExternal(PendingAddArguments pendingAddArguments)
	{
		switch (pendingAddArguments.requestCode) {
		case REQUEST_CREATE_DIALER_SHORTCUT:
			completeAddDialerShortcut(pendingAddArguments);
			break;

		case REQUEST_PICK_APP:
			completeAddAppFromExternal(pendingAddArguments);
			break;
		}
	}
	
	// 创建联系人快捷方式
	private SimpleBubbleView createShortcutBubbleView(int resource, ViewGroup root, SimpleItemInfo item) 
	{
		SimpleBubbleView bubbleView = (SimpleBubbleView)mInflater.inflate(resource, root, false);
		bubbleView.applyContactShortcutBubbleView(item);
		bubbleView.setOnClickListener(this);
		
		return bubbleView;
	}
	
	// 进入编辑模式
	private void enterSimpleEditMode() {
		editButtonVisibilityChange(true);
		mSimpleWorkspace.changeStateAnimated(State.EDIT);
		showDeleteHatTip();
		fullScreen(true);
		
		invalidateBubbleTextViews();
	}

	// 退出编辑模式
	private void exitSimpleEditMode() {
		if (mState == State.EDIT && mSimpleWorkspace.getChangeStateAnimatingIsEnd()) 
		{
			editButtonVisibilityChange(false);
			mSimpleWorkspace.changeStateAnimated(State.NORMAL);
			dismissDeleteTextView();
			fullScreen(false);
			
			invalidateBubbleTextViews();
		}
	}
	
	// 编辑按钮显示改变动画
	public void editButtonVisibilityChange(boolean isShowEditButton)
	{
	    final int buttonHeight, pageIndicatorBottomMargin, editButtonBottomMargin;
	    final FrameLayout.LayoutParams lpPageIndicator;
	    final FrameLayout.LayoutParams lpEditBtn;
	    
	    if (mEditDoneButton != null)
	    {
	      buttonHeight = mEditDoneButton.getHeight();
	      if (mEditAnimtor == null)
	          mEditAnimtor = ValueAnimator.ofFloat(new float[] { 0.0F, 1.0F }).setDuration(mDuration);
	      
	      lpPageIndicator = (FrameLayout.LayoutParams)(FrameLayout.LayoutParams)mSimpleQuickNavigation.getLayoutParams();
	      pageIndicatorBottomMargin = lpPageIndicator.bottomMargin;
	      
	      lpEditBtn = (FrameLayout.LayoutParams)(FrameLayout.LayoutParams)mEditDoneButton.getLayoutParams();
	      editButtonBottomMargin = lpEditBtn.bottomMargin;
	      
	      mEditAnimtor.removeAllUpdateListeners();
	      
	      if (isShowEditButton){
		      mEditAnimtor.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
		      {
		        public void onAnimationUpdate(ValueAnimator animator)
		        {
		          float value = ((Float)animator.getAnimatedValue()).floatValue();
		          Log.d(TAG, ">>>>>###1mEditAnimtor onAnimationUpdate, value=" + value);
		          
		          lpPageIndicator.bottomMargin = (pageIndicatorBottomMargin + (int)(value * buttonHeight));
		          lpEditBtn.bottomMargin = (editButtonBottomMargin + (int)(value * buttonHeight));
		          mSimpleQuickNavigation.requestLayout();
		          mEditDoneButton.requestLayout();
		        }
		      });
	      }else{
	    	mEditAnimtor.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
	  	    {
	  	      public void onAnimationUpdate(ValueAnimator animator)
	  	      {
	  	        float value = ((Float)animator.getAnimatedValue()).floatValue();
	  	        Log.d(TAG, ">>>>>###2mEditAnimtor onAnimationUpdate, value=" + value);
	  	      
	  	        lpPageIndicator.bottomMargin = (pageIndicatorBottomMargin - (int)(value * buttonHeight));
	  	      	lpEditBtn.bottomMargin = (editButtonBottomMargin - (int)(value * buttonHeight));
	  	        mEditDoneButton.requestLayout();
	  	        mSimpleQuickNavigation.requestLayout();
	  	      }
	  	    });
	      }
	    }
	}
	
	public void fullScreen(boolean flag) 
	{
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		
		if (flag) {
			lp.flags = (WindowManager.LayoutParams.FLAG_FULLSCREEN | lp.flags);
			getWindow().setAttributes(lp);
			return;
		}
		
		lp.flags = (0xFFFFFBFF & lp.flags);
		getWindow().setAttributes(lp);
	}
	
	// 隐藏上方的提示文本
	public void dismissDeleteTextView() {
		mHatTip.setVisibility(View.GONE);
	}
	
	public static Handler getSimpleUILauncherHandler() {
		return sSimpleUILauncherHandler;
	}
	
	// 删除桌面的BubbleView和缓存中的item
	private void removeViewAndItemInfo(SimpleItemInfo item) 
	{
		if (item != null) {
			SimpleCellLayout cellLayout = (SimpleCellLayout)mSimpleWorkspace.getChildAt(item.screen);
			View v = cellLayout.getChildAt(item.cellX, item.cellY);
			if ((v instanceof SimpleBubbleView))
				((SimpleBubbleView)v).recycleBubbleView();
			
			cellLayout.removeView(v);
			SimpleLauncherModel.sFavoriteItems.remove(item);
		}else{
			Log.w(TAG, "SimpleUILauncher removeViewAndItemInfo(SimpleItemInfo info) info is null!");
		}
	}
	
	public static void setFolderActiviytHanlder(Handler handler) {
		sFolderHandler = handler;
	}
	
	// 添加联系人快捷方式到桌面
	private void startAddingPeopleShortcut() {
		ComponentName componentName = new ComponentName("com.android.contacts", "com.android.contacts.ContactShortcut");
		Intent intent = new Intent("android.intent.action.CREATE_SHORTCUT");
		intent.setComponent(componentName);
		startActivityForResultSafely(intent, REQUEST_CREATE_DIALER_SHORTCUT);
		dismissDeleteTextView();
		fullScreen(false);
	}

	// 添加app到桌面
	private void startAllApps() {
		ComponentName componentName = new ComponentName(getPackageName(), AddApplication.class.getName());
		Intent intent = new Intent("android.intent.action.CREATE_SHORTCUT");
		intent.setComponent(componentName);
		startActivityForResult(intent, REQUEST_PICK_APP);
		overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_open_exit);
		dismissDeleteTextView();
		fullScreen(false);
	}
	
	private void startFolder(String folderName) {
		//Intent intent = new Intent(this, SimpleFolder.class);
		Intent intent = new Intent("com.tozed.launcher.simpleuifolder");
		intent.putExtra("folderName", folderName);
		startActivityForResultSafely(intent, REQUEST_OPEN_FOLDER);
		overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_open_exit);
	}
	
	public void showToast(String strToast){
		Toast.makeText(this, strToast, Toast.LENGTH_SHORT).show();
	}
	
	void startActivityForResultSafely(Intent intent, int requestCode) {
		Log.i(TAG, "SimpleUILauncher startActivityForResultSafely");
		try {
			startActivityForResult(intent, requestCode);
		} catch (ActivityNotFoundException e) {
			//LauncherApplication.showToast(2131427337, 0);
		} catch (SecurityException ex) {
			//LauncherApplication.showToast(2131427337, 0);
			Log.e(TAG, "SimpleUILauncher Launcher does not have the permission to launch "
							+ intent
							+ ". Make sure to create a MAIN intent-filter for the corresponding activity "
							+ "or use the exported attribute for this activity.",
							ex);
		}
	}
	
	public void layoutNavigationPoint(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
		layoutNavigationPoint();
	}
	
	public void layoutNavigationPoint()
	{
	    int editButtonHeight = getResources().getDimensionPixelSize(R.dimen.edit_done_button_height);
	    
	    SimpleCellLayout cellLayout = (SimpleCellLayout)getWorkspace().getChildAt(0);
	    if (cellLayout == null)
	       return;
	    
	    int cellLayoutBottom;
	    int height;
	    int bottomMargin = 0;
	    
		if (mState == State.EDIT)
		{
			cellLayoutBottom = cellLayout.getCellLayoutBottom(true, this);
			height = mSimpleWorkspace.getMeasuredHeight() - editButtonHeight;
		}else{
			cellLayoutBottom = cellLayout.getCellLayoutBottom(false, this);
			height = mSimpleWorkspace.getMeasuredHeight();
		}
		
		int pageIndicatorHeight = mSimpleQuickNavigation.getMeasuredHeight();
		int result = (height - cellLayoutBottom - pageIndicatorHeight) / 2;

		if (mState != State.EDIT)
			editButtonHeight = 0;

		bottomMargin = result + editButtonHeight;
		if (bottomMargin < 0)
			bottomMargin = 0;

	    FrameLayout.LayoutParams lpPageIndicator = (FrameLayout.LayoutParams)mSimpleQuickNavigation.getLayoutParams();
	    lpPageIndicator.bottomMargin = bottomMargin;
	    mSimpleQuickNavigation.requestLayout();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i(TAG, "SimpleUILauncher onActivityResult, requestCode=" + requestCode + ",resultCode=" + resultCode);
		
		if (resultCode == RESULT_OK) {
			PendingAddArguments pendingAddArguments = new PendingAddArguments();
			pendingAddArguments.requestCode = requestCode;
			pendingAddArguments.intent = data;
			completeAddFromExternal(pendingAddArguments);
		}
	}

	private void unregisterUnreadListener()
	{
		
	}

	public SimpleWorkspace getWorkspace(){
		return mSimpleWorkspace;
	}

	// 在UI线程中刷新视图
	public void invalidateBubbleTextViews()
	{
		Log.d(TAG, "invalidateBubbleTextViews");
		int cellCount = mSimpleWorkspace.getChildCount();
		for (int i = 0; i < cellCount; i++)
	    {
	      SimpleCellLayout cellLayout = (SimpleCellLayout)mSimpleWorkspace.getChildAt(i);
	      int viewCountOfCell = cellLayout.getChildCount();
	      
			for (int j = 0; j < viewCountOfCell; j++)
			{
				View view = cellLayout.getChildAt(j);
				SimpleBubbleView bubbleView;

				if (view instanceof SimpleBubbleView)
				{
					bubbleView = (SimpleBubbleView)view;
					
					//Log.e(TAG, "invalidateBubbleTextViews, mode=" + getMode() 
					//		+ ",isRemovable=" + bubbleView.isRemovable());
					
					if (getMode() == State.EDIT && bubbleView.isRemovable())
						bubbleView.setRemoveVisibility(View.VISIBLE);
					else
						bubbleView.setRemoveVisibility(View.GONE);
				}
			}
			
			cellLayout.invalidate();
	    }
	}
	
	// 绑定小插件
	public void bindAppWidget(SimpleLauncherAppWidgetInfo item)
	{
		if (item == null)
			return;

		final long start = DEBUG ? SystemClock.uptimeMillis() : 0;

		final SimpleWorkspace simpleWorkspace = mSimpleWorkspace;
		int appWidgetId = item.appWidgetId;
		
		try
		{
			AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
			Log.d(TAG, "SimpleUILauncher bindAppWidget appWidgetId:" + appWidgetId + ", component " + appWidgetInfo.provider);
			
			item.hostView = mSimpleAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
			item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
			item.hostView.setTag(item);

			// 添加widget小插件到桌面中
			simpleWorkspace.addViewInScreen(item.hostView, item.screen, item.cellX, item.cellY, item.spanX, item.spanY, false);
			addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
			simpleWorkspace.requestLayout();

			Log.d(TAG,"SimpleUILauncher bound widget id=" + item.appWidgetId + " in " + (SystemClock.uptimeMillis()-start) + "ms");
		} catch (Exception e){
			Log.e(TAG, "SimpleUILauncher no permision to call bindAppWidgetId", e);
		}
	}
	
	// 实现SimpleLauncherModel.Callbacks中的方法
	@Override
	public void startBinding()
	{
		final SimpleWorkspace simpleWorkspace = mSimpleWorkspace;
		int count = simpleWorkspace.getChildCount();
		for (int i = 0; i < count; i++)
			((SimpleCellLayout)simpleWorkspace.getChildAt(i)).removeAllViewsInLayout();
		
		mWidgetsToAdvance.clear();
		resetCellOccupied();
		mIsFinishBindingItems = false;
	}

	// 实现SimpleLauncherModel.Callbacks中的方法
	// 直正添加到主工作区workspace的CellLayout中的view的方法
	@Override
	public void bindItems(List<SimpleItemInfo> shortcuts, int start, int end)
	{
		if (shortcuts == null || shortcuts.size() == 0)
	       return;
		
	    final SimpleWorkspace simpleWorkspace = mSimpleWorkspace;
		for (int i = start; i < end; i++)
		{
			final SimpleItemInfo item = shortcuts.get(i);		
			switch (item.itemType){
				case SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_APPLICATION:
					if (item instanceof SimpleApplicationInfo){
				        SimpleBubbleView bubbleView = (SimpleBubbleView)createBubbleView(R.layout.simple_bubble_view, 
				        			(ViewGroup)simpleWorkspace.getChildAt(item.screen), (SimpleApplicationInfo)item);
				        simpleWorkspace.addViewInScreen(bubbleView, item.screen, item.cellX, item.cellY, 1, 1, false);
					}
					break;
					
				case SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_SHORTCUT:
					SimpleBubbleView bubbleView = createShortcutBubbleView(R.layout.simple_bubble_view, 
									(ViewGroup)this.mSimpleWorkspace.getChildAt(item.screen), item);
					simpleWorkspace.addViewInScreen(bubbleView, item.screen, item.cellX, item.cellY, 1, 1, false);
				    break;
				    
				case SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_FOLDER:
					addFolderToWorkspace(item);
					break;
			}
		}
		
		simpleWorkspace.requestLayout();
	}

	// 实现SimpleLauncherModel.Callbacks中的方法
	@Override
	public void bindFolders(List<SimpleItemInfo> folders)
	{
		//Log.d(TAG, "bindFolders size="  + folders.size());
		for (int i = 0; i < folders.size(); i++) 
		{
			SimpleItemInfo item = (SimpleItemInfo) folders.get(i);
			if (item != null) {
				SimpleFolderIcon folderIcon = (SimpleFolderIcon)item.getView();
				if (folderIcon != null) {
					folderIcon.setContentApps(); // 设置文件夹图标预览内容
					folderIcon.invalidate();
				}
			}
		}
	}

	// 实现SimpleLauncherModel.Callbacks中的方法
	@Override
	public void finishBindingItems()
	{
		mIsFinishBindingItems = true;
	    mSimpleModel.getWorker().post(mUpdateMissInfoSignRunnable);
	}

	// 实现SimpleLauncherModel.Callbacks中的方法
	@Override
	public void bindWidgets(List<SimpleLauncherAppWidgetInfo> appWidgetInfos)
	{
		int size = appWidgetInfos.size();
		Log.i(TAG, "SimpleUILauncher bindWidgets size:" + size);
			
		for (int i = 0; i < size; i++)
			bindAppWidget((SimpleLauncherAppWidgetInfo)appWidgetInfos.get(i));
	}

	// 实现SimpleLauncherModel.Callbacks中的方法
	@Override
	public void bindAppsAdded(ArrayList<SimpleApplicationInfo> apps, boolean flag)
	{
		//Log.e(TAG, "SimpleUILauncher bindAppsAdded apps.size=" + apps.size());
		int size = apps.size();
		
		for (int i = 0; i < size; i++)
		{
			SimpleApplicationInfo appInfo = (SimpleApplicationInfo) apps.get(i);
			if (!flag && mSimpleModel.getDataInDb(this,appInfo) && appInfo.container == -100L 
					&& mSimpleWorkspace.addItemInfoToOriPisition(appInfo))
			{
				SimpleLauncherModel.addItemToDatabase(this, appInfo, false);
			}else{
				// 添加到文件夹并更新
				mSimpleModel.addItemIntoFolder(appInfo, appInfo.isBelongToDownloadFolder(getPackageManager()));
			}
		}
	}

	// 实现SimpleLauncherModel.Callbacks中的方法
	@Override
	public void bindAppsRemoved(ArrayList<SimpleApplicationInfo> apps, boolean flag)
	{
		//Log.e(TAG, "SimpleUILauncher bindAppsRemoved apps.size=" + apps.size());
		
		int size = apps.size();
		for (int i = 0; i < size; i++)
		{
			// APP被删除,桌面相应的视图也要删除
			SimpleApplicationInfo appInfo = (SimpleApplicationInfo) apps.get(i);
			boolean isRemove = mSimpleWorkspace.removeItemFromWorkspace(appInfo);
			//Log.e(TAG, "SimpleUILauncher bindAppsRemoved isRemove=" + isRemove);
			
			// 更新文件夹内容 
			if (isRemove) {
				//Log.e(TAG, "SimpleUILauncher deleteItemFromDatabase " + appInfo.title);
				SimpleLauncherModel.deleteAppFromDatabase(this,appInfo, flag);
				
				// 已删除的应用不能再用isBelongToDownloadFolder方法来判断,应用包名已找不到
				//mSimpleModel.removeItemfromFolder(appInfo, appInfo.isBelongToDownloadFolder(getPackageManager()));
				boolean isDownloadApp = (appInfo.flags & SimpleApplicationInfo.DOWNLOADED_FLAG) != 0;
				mSimpleModel.removeItemfromFolder(appInfo, isDownloadApp);
			}
		}
		
		// 显示"添加"项
		bindNeedAddedItemsAndSave();
	}

	// 实现SimpleLauncherModel.Callbacks中的方法
	@Override
	public void bindAppsUpdated(ArrayList<SimpleApplicationInfo> apps)
	{
		 if (mSimpleWorkspace != null)
		    mSimpleWorkspace.updateApplications(apps);
	}

	// 实现SimpleLauncherModel.Callbacks中的方法
	@Override
	public void bindNeedAddedItemsAndSave()
	{
		mNeedAddedItemName = getResources().getString(R.string.str_need_added_item_name);
	    int count = mSimpleWorkspace.getChildCount();
	    for (int i = 0; i < count; i++)
	    	bindNeedAddedItems((SimpleCellLayout)mSimpleWorkspace.getChildAt(i));
	}
	
	// 实现SimpleLauncherModel.Callbacks中的方法
	@Override
	public boolean isAllAppsVisible()
	{
		// TODO Auto-generated method stub
		return false;
	}
	
	// 实现SimpleLauncherModel.Callbacks中的方法
	// 未读电话、短信、Email
	@Override
	public void bindUnreadNumberUpdated(int type, int number)
	{
		Log.d(TAG, "bindUnreadNumberUpdated type = "+ type + " number = " + number);
		
		if (type == 0){ 	// missed call
			updateUnreadMark("com.android.dialer", "com.android.dialer.DialtactsActivity", number);
		}else if (type == 1){ // sms
			updateUnreadMark("com.android.mms", "com.android.mms.ui.ConversationList", number);
		}
	}
	
	public boolean isFinishBindingItems(){
		return mIsFinishBindingItems;
	}
	
	void closeSystemDialogs()
	{
		getWindow().closeAllPanels();
		try{
			dismissDialog(SIMPLE_DIALOG_CREATE);
			return;
		} catch (Exception e){
			Log.e(TAG, "SimpleUILauncher dialog dismiss failed : " + e);
		}
	}
	
	public void dealTextViewOutLine(View view)
	{
		mClickView = view;
		if (view instanceof SimpleFolderIcon)
		{
			SimpleFolderIcon folderIcon = (SimpleFolderIcon)view;
			folderIcon.setPressed(true);
			folderIcon.invalidate();
			mHandler.sendEmptyMessageDelayed(REMOVE_OUT_LINE_MESSAGE, 50);
		}else if (view instanceof SimpleBubbleView){
			SimpleBubbleView bubbleView = (SimpleBubbleView)view;
			bubbleView.setPressed(true);
			bubbleView.invalidate();
			mHandler.sendEmptyMessageDelayed(REMOVE_OUT_LINE_MESSAGE, 50);
		}
	}
	
	public void resetCellOccupied(){
		int count = mSimpleWorkspace.getChildCount();
		for (int i = 0; i < count; i++)
			((SimpleCellLayout)mSimpleWorkspace.getChildAt(i)).clearOccupiedCells();
	}
	
	public void resetCallIntent(SimpleItemInfo item)
	{
		
	}

	public void setMode(State state){
	    mState = state;
	}

	public SimplePageIndicator getSimplePageIndicatior(){
		return mSimpleQuickNavigation;
	}

	public SimpleLauncherModel getSimpleModel(){
		return mSimpleModel;
	}

	public SimpleBubbleView createBubbleView(int layoutId, ViewGroup viewGroup, SimpleApplicationInfo app)
	{
		SimpleBubbleView bubbleView = (SimpleBubbleView)mInflater.inflate(layoutId, viewGroup, false);
		if (app.itemType == SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_NEED_ADDED)
			bubbleView.applyAddIconFromBubbleView(app);
		else{
			if (app.isPresetApp){
				bubbleView.applyPresetAppFromBubbleView(app);
			}else{
				bubbleView.applyOtherAppFromBubbleView(app);
			}
		}
		
		bubbleView.setOnClickListener(this);
		return bubbleView;
	}
	
	public boolean isMotionDetectAvailable(){
		//return LauncherApplication.isMotionDetectAvailable();
		return false;
	}

	@Override
	public void onAttachedToWindow(){
		super.onAttachedToWindow();
		
		// Listen for broadcasts related to user-presence
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        registerReceiver(mReceiver, filter);
        FirstFrameAnimatorHelper.initializeDrawListener(getWindow().getDecorView());
        
        mAttached = true;
        mVisible = true;
	}

	@Override
	public void onBackPressed(){
		exitSimpleEditMode();
	}

	@Override
	public boolean onLongClick(View v){
		Log.d(TAG, "onLongClick, mState=" + mState + ",allowLongPress=" + mSimpleWorkspace.allowLongPress()
				+ ",getChangeStateAnimatingIsEnd=" + mSimpleWorkspace.getChangeStateAnimatingIsEnd());
		
		boolean isSimpleLargeScreen = LauncherApplication.isSimpleScreenLarge();
		if (isSimpleLargeScreen == false){
			if (mState == State.NORMAL && mSimpleWorkspace.allowLongPress()
					&& mSimpleWorkspace.getChangeStateAnimatingIsEnd())
			{
				mVibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
				mVibrator.vibrate(35);
				enterSimpleEditMode();
			}
		}
		
		return true;
	}
	
	@Override
	public void onClick(View v)
	{
	    dealTextViewOutLine(v);
	    
	    Object object = v.getTag();
	    SimpleItemInfo itemInfo = (SimpleItemInfo)object;
	    if (itemInfo == null){
	    	Log.e(TAG, "target itemInfo is null.");
	    	return;
	    }
	    
	    switch (itemInfo.itemType)
	    {
		    case SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_APPLICATION:
		    {
		    	SimpleApplicationInfo app = (SimpleApplicationInfo)v.getTag();
				if (mState == State.NORMAL){
					if (app.isNormalHome){
						//HomeSwitcher.changeHomeTo(this, LauncherApplication.UNIHOME_COMPONENT);
						//return;
					}
					
					//Log.e(TAG, "######INTENT=" + app.intent.toString());
					//SimpleUtilities.startActivitySafely(getApplicationContext(), app.intent, object);
					startActivitySafelyInternal(this, app.intent, object);
				}else{
					// 编辑模式单击时就删除并更新视图
					if (!app.isFixedPosition)
					{
						// 删除应用视图和数据库中的收藏项
				        removeViewAndItemInfo(app);
				        SimpleLauncherModel.deleteAppFromDatabase(mApp, app, true);
				        boolean isDownloadApp = app.isBelongToDownloadFolder(getPackageManager());
				        
				        // 重新添加回文件夹缓存中
				        mApp.getSimpleModel().addItemIntoFolder(app, isDownloadApp);
				        
				        // 修改该位置为添加状态视图
				        SimpleApplicationInfo appNeedAdd = createNeedAddedItem(app.screen, app.cellX, app.cellY);
				        SimpleBubbleView bubbleView = createBubbleView(R.layout.simple_bubble_view, 
				        		(ViewGroup)mSimpleWorkspace.getChildAt(app.screen), appNeedAdd);
				        mSimpleWorkspace.addViewInScreen(bubbleView, app.screen, app.cellX, app.cellY, 1, 1, false);
				        
				        SimpleUtilities.sendAccessibilityEvent(getString(R.string.str_simple_view_removed, new Object[] {itemInfo.title}));
				      }else{
				    	  //  无法删除系统应用提示
				    	  DoTaskOnceAtFirstOrAtLast.doTaskOnceAtFirst(mShowToastOnceAtFirstRunnable);
				      }
				}
		    }
	    	break;
	    	
		    case SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_SHORTCUT:
	    	{
	    		if (mState == State.NORMAL){
	    			//SimpleUtilities.startActivitySafely(getApplicationContext(), itemInfo.intent, object);
	    			startActivitySafelyInternal(this, itemInfo.intent, object);
	  	      	}else{
	  	      		removeViewAndItemInfo(itemInfo);
	  	      		SimpleLauncherModel.deleteItemInfoFromDatabase(mApp, itemInfo);
	  	      		SimpleApplicationInfo appNeedAdd = createNeedAddedItem(itemInfo.screen, itemInfo.cellX, itemInfo.cellY);
	  	      		SimpleBubbleView bubbleView = createBubbleView(R.layout.simple_bubble_view, (ViewGroup)mSimpleWorkspace.getChildAt(itemInfo.screen), appNeedAdd);
	  	      		mSimpleWorkspace.addViewInScreen(bubbleView, itemInfo.screen, itemInfo.cellX, itemInfo.cellY, 1, 1, false);
	  	      	}
	    	}
	    	break;
	    	
		    case SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_FOLDER:
		    {
		    	 if (mState == State.EDIT){
			        DoTaskOnceAtFirstOrAtLast.doTaskOnceAtFirst(mShowToastOnceAtFirstRunnable);
			      }else{
				      if (!mIsFinishBindingItems){
				        showContentLoadingToast();
				      }else{
				    	  mPendingAddInfo = itemInfo;
				    	  int resId = getResources().getIdentifier(itemInfo.title.toString(), "string", "com.tozed.android.launcher");
				    	  if (resId != -1 && resId != 0){
					    	  try {
					    		  startFolder(getResources().getString(resId));
					    	  } catch (NotFoundException e) { }
				    	  }else{
				    		  startFolder(itemInfo.title.toString());
				    	  }
				      }
			      }
		    }
		    break;
		    	
		    case SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_NEED_ADDED:
			      mPendingAddInfo = itemInfo;
			      showAddDialog();
			      v.postInvalidate();
		    	break;
		    	
		    case SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_APPWIDGET:
		    	DoTaskOnceAtFirstOrAtLast.doTaskOnceAtFirst(mShowToastOnceAtFirstRunnable);
		    	break;
	    }
	}
	
	public boolean startActivitySafelyInternal(Context context, Intent intent, Object tag)
	{
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		try{
			context.startActivity(intent);
			//overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
			overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_open_exit);
			//overridePendingTransition(R.anim.task_open_enter, R.anim.task_open_exit);
			return true;
		}catch (ActivityNotFoundException e) {
			Toast.makeText(context, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
	        Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
		}catch (SecurityException e){
			 Toast.makeText(context, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
	         Log.e(TAG, "Launcher does not have the permission to launch " + intent, e);
		}
		
		return false;
	}
	
	@Override
	protected void onNewIntent(Intent intent){
		super.onNewIntent(intent);
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		
		if (mMotionManager == null)
			return;
		
		//mMotionManager.removeProxyDetectionListener();
		//mMotionManager.removeResultListener(this.mShakeWallpaperMotionResultListener);
		//mMotionManager.stopShakePrivacyMotion();
	}
	
	@Override
	protected void onStart()
	{
		//overridePendingTransition(0, 0); // not use animation
		//overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
		overridePendingTransition(R.anim.activity_close_enter, R.anim.activity_close_exit);
		//overridePendingTransition(R.anim.task_close_enter, R.anim.task_close_exit);
		super.onStart();
	}

	@Override
	protected void onResume()
	{
		super.onResume();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle bundle)
	{
		super.onSaveInstanceState(bundle);
		
		bundle.putInt("simpleLauncher.current_screen", mSimpleWorkspace.getCurrentScreen());
		if (this.mPendingAddInfo.container == -1L || mPendingAddInfo.screen <= -1)
			return;
		
		bundle.putLong("simpleLauncher.add_container", mPendingAddInfo.container);
		bundle.putInt("simpleLauncher.add_screen",  mPendingAddInfo.screen);
		bundle.putInt("simpleLauncher.add_cell_x",  mPendingAddInfo.cellX);
		bundle.putInt("simpleLauncher.add_cell_y",  mPendingAddInfo.cellY);
	}

	@Override
	protected Dialog onCreateDialog(int dialogId)
	{
		switch (dialogId){
		case SIMPLE_DIALOG_CREATE:
			return new CreateShortcut().createGridDialog();
		}
		
		return super.onCreateDialog(dialogId);
	}

	@Override
	protected void onDestroy(){
		super.onDestroy();
		
		unregisterUnreadListener();
	    try
	    {
	      mSimpleAppWidgetHost.stopListening();
	      mSimpleAppWidgetHost = null;
	      
	      if (mMotionManager != null)
	        //mMotionManager.destoryMotionDetectionManager();
	      
	      AddApplicationViewCache.getInstance().clear();
	      sSimpleUILauncherHandler = null;
	      ((ViewGroup)mSimpleWorkspace.getParent()).removeAllViews();
	      mSimpleWorkspace.clearChildren();
	      mSimpleWorkspace.removeAllViews();
	    }catch (NullPointerException e){
	      Log.e(TAG, "SimpleUILauncher problem while stopping AppWidgetHost during Launcher destruction", e);
	    }
	}
	
	public void onDetachedFromWindow()
	{
		super.onDetachedFromWindow();
		
		mVisible = false;
		if (mAttached){
			unregisterReceiver(mReceiver);
			mAttached = false;
		}
		updateRunning();
	}

	public ValueAnimator getEditAnimtor(){
		return mEditAnimtor;
	}



	public State getMode(){
		return mState;
	}

	public MotionManager getMotionManager(){
		return mMotionManager;
	}

	public String getIconBgString(String pkgName)
	{
		if ((pkgName == null) || (mIconBgStrings.length == 0))
			return "bg_grey";

		int hashCode = pkgName.hashCode();
		int abs = 0;

		if (hashCode != Integer.MIN_VALUE)
			abs = Math.abs(pkgName.hashCode());

		int index = abs % mIconBgStrings.length;
		return mIconBgStrings[index];
	}
	
	private void showAddDialog() {
		showDialog(SIMPLE_DIALOG_CREATE);
	}
	
	private void showContentLoadingToast()
	{
		DoTaskOnceAtFirstOrAtLast.doTaskOnceAtFirst(new Runnable(){
			public void run(){
				Toast.makeText(SimpleUILauncher.this, R.string.str_content_loading, Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	// 更新未读消息
	public void updateUnreadMark(String strPkgName, String strClsName, int nUnreadNum) {
	    if ((strPkgName == null) || (strClsName == null))
	        return;
	    
	      // 更新桌面上的BubbleView的未读标志
	      View iconView = mSimpleWorkspace.getIconView(strPkgName, strClsName);
	      if ((iconView != null) && (iconView instanceof SimpleBubbleView))
	      {
	        ((SimpleBubbleView)iconView).setUnreadNum(nUnreadNum);
	        SimpleItemInfo item = (SimpleItemInfo)iconView.getTag();
	        item.setUnReadNum(nUnreadNum);
	        resetCallIntent(item);
	      }
	      
	      ArrayList<SimpleApplicationInfo> apps = new ArrayList<SimpleApplicationInfo>();
	      apps.addAll(SimpleLauncherModel.sDownloadApps);
	      apps.addAll(SimpleLauncherModel.sOtherApps);
	      
	      for (SimpleApplicationInfo appInfo : apps)
	      {
	    	  if (appInfo == null)
	    		  continue;
	    	  
	    	  if (appInfo.container == SimpleLauncherSettings.SimpleFavorites.CONTAINER_DESKTOP)
	    		  continue;
	    	  
	    	  String pkgName = appInfo.getPkgName();
	    	  if (pkgName == null || !pkgName.equalsIgnoreCase(strPkgName))
	    		  continue;
	    	  
	    	  String clsName = appInfo.getClsName();
	    	  if (clsName == null || !clsName.equalsIgnoreCase(strClsName))
	    		  continue;
	    	  
	    	  appInfo.setUnReadNum(nUnreadNum);
	    	  resetCallIntent(appInfo);
	    	  
	    	  // 更新文件夹内的APP未读标志
	    	  if (sFolderHandler != null){
		          Message msg = new Message();
		          msg.obj = appInfo;
		          msg.what = SimpleFolder.UNREAD_NUM_UPDATE;
		          sFolderHandler.sendMessage(msg);
		          Log.i(TAG, "SimpleUILauncher sendMessge unReadNum=" + nUnreadNum + " class=" + clsName);
	    	  }else{
	    		  Log.w(TAG, "SimpleUILauncher Handler simpleFolder activity is null when update view");
	    	  }
	      }
	}
	
	// 添加快捷方式对话框
	private class CreateShortcut implements DialogInterface.OnClickListener,
			DialogInterface.OnCancelListener,
			DialogInterface.OnDismissListener, DialogInterface.OnShowListener,
			AdapterView.OnItemClickListener 
	{
		
		private void cleanup() {
			try{
				SimpleUILauncher.this.dismissDialog(SIMPLE_DIALOG_CREATE);
			} catch (Exception e){
				Log.e(TAG, "SimpleUILauncher dialog dismiss failed : " + e);
			}
	    }
		
		Dialog createGridDialog()
	    {
	      mDialogMenuGrid.setOnItemClickListener(this);
	      AlertDialog dlg = mDialogBuilder.create();
	      dlg.setOnCancelListener(this);
	      dlg.setOnDismissListener(this);
	      dlg.setOnShowListener(this);
	      dlg.setCanceledOnTouchOutside(true);
	      return dlg;
	    }

		@Override
		public void onShow(DialogInterface arg0) {
			
		}

		@Override
		public void onDismiss(DialogInterface arg0) {
			cleanup();
		}

		@Override
		public void onCancel(DialogInterface arg0) {
			cleanup();
		}

		@Override
		public void onClick(DialogInterface arg0, int arg1) {
			cleanup();
		}

		@Override
		public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt, long paramLong) {
			cleanup();
			
			int key = ((SimpleAddAdapter.ListItem)mAdapter.getItem(paramInt)).actionTag;
			switch (key){
			case SimpleAddAdapter.ITEM_PEOPLE_SHORTCUT:
				startAddingPeopleShortcut();
				break;
			case SimpleAddAdapter.ITEM_ADD_APPS:
				startAllApps();
				break;
			}
		}

	}
	
	private static class PendingAddArguments {
		Intent intent;
		int requestCode;
	}
	
	class PrivacyModeShakeSwitchContent extends ContentObserver
	{
		public PrivacyModeShakeSwitchContent(Handler handler){
			super(handler);
		}
		
		@Override
		public void onChange(boolean selfChange)
		{
			super.onChange(selfChange);
			
			ContentResolver cr = SimpleUILauncher.this.getContentResolver();
			if (android.provider.Settings.System.getInt(cr, "motion_shake_start_privacy", 1) == 1)
			{
				SimpleUILauncher.this.mApp.setIsShakeInHome(true);
				Log.i(TAG, "SimpleUILauncher onChange selfChange=" + selfChange + " isShakeOnHome=" + 1);
			}
		}
	}
}
